/**
 * Copyright © 2014 Creativor Studio. About license information, please see
 * LICENSE.txt.
 */
package org.rayson.server.rpc;

import java.util.Map.Entry;

import org.rayson.api.KeyValues;
import org.rayson.api.exception.RpcException;
import org.rayson.api.server.ServerResponse;
import org.rayson.api.struct.HttpResponseStatus;
import org.rayson.server.http.HttpServerResponse;
import org.rayson.share.http.HttpConstants;
import org.rayson.share.http.HttpHeader;
import org.rayson.share.http.HttpStatusLine;

public class ServerResponseImpl implements ServerResponse {

	private static HttpStatusLine HTTP_STATUS_OK = new HttpStatusLine(
			HttpConstants.HTTP_VERSION, HttpResponseStatus.OK);

	private final ServerRequestImpl request;

	private RpcException exception;

	private Object result;

	private final KeyValues headers;

	/**
	 * @param requestImpl
	 */
	public ServerResponseImpl(final ServerRequestImpl requestImpl) {
		this.request = requestImpl;
		this.headers = new KeyValues();
	}

	@Override
	public RpcException getException() {
		return exception;
	}

	@Override
	public KeyValues getHeaders() {
		return headers;
	}

	@Override
	public Object getResult() throws RpcException {
		if (gotException())
			throw exception;
		return result;
	}

	private boolean gotException() {
		return exception != null;
	}

	@Override
	public void setException(final RpcException rpcException) {
		this.exception = rpcException;
	}

	@Override
	public void setResult(final Object result) {
		this.result = result;
	}

	@Override
	public HttpServerResponse toHttpResponse() {
		// Convert RPC response to HTTP response.
		final HttpServerResponse httpRes = new HttpServerResponse();
		for (final Entry<String, String> header : headers.entrySet()) {
			httpRes.addHeader(new HttpHeader(header.getKey(), header.getValue()));
		}

		// Set status line.
		HttpStatusLine startLine = HTTP_STATUS_OK.clone();
		if(gotException()){
			startLine=new HttpStatusLine(exception.getCode(),exception.getMessage());
		}
		httpRes.setStartLine(startLine);
		
		// Set body.
		
		return httpRes;
	}
}